<template>
  <div class="homeMain">
    <div class="headBar" >
      <el-row>
        <el-col :span="8" class="title">
            <el-image
              style="width:100%; height: 100px"
              fit="contain"
              src="../../../logo.png"
            ></el-image>
        </el-col>
        <el-col :span="13" class="logoLine">
          管理机构和教辅机构年度考评系统
        </el-col>
        <el-col :span="2" class="textPlac">
          <el-button type="text" class="fontColor" @click="dialogFormVisible = true"> 修改密码</el-button>
        </el-col>
        <el-col :span="1" class="textPlac">
          <el-button type="text" class="fontColor" @click="onHandleCommandClick"> 退出登录</el-button>
        </el-col>
      </el-row>
    </div>
    <el-empty v-if="itemList.length==0" description="您已完成全部考评"></el-empty>
    <el-tabs class="mainPain " v-model="activeName">
      <el-tab-pane class="tab-pane" v-for="(item,index) in itemList" :key="item" :label="'\xa0\xa0\xa0' +item+'\xa0\xa0\xa0'" :name="item">
        <div class="assInfoBox">
          <div class="infoRow"> <el-icon><elementCalendar/></el-icon> 开始时间: {{startTime}}  <el-icon><elementCalendar/></el-icon> 结束时间:  {{endTime}}</div>
          <!-- <div class="infoRow"> <el-icon><elementChatLineSquare /></el-icon> 考核名称： {{assName}} </div> -->

          <div v-if="scoreList[index].length > 1">
            <div v-for="(name,index) in scoreTypeName" :key="name" class="infoRow">
              <el-icon><elementInfoFilled /></el-icon>  {{name}} :
              <span class="fontName"> "{{scoreName[index][0]}}"</span>个数最大为<span class="fontNum"> {{scoreMaxNum[index][0]}}</span>,已评<span class="fontNum"> {{scoreNum[index][0]}}</span>
              <!-- |<span class="fontName"> "{{scoreName[index][1]}}"</span>个数最大为<span class="fontNum"> {{scoreMaxNum[index][1]}}</span>,已评<span class="fontNum"> {{scoreNum[index][1]}}</span> -->
            </div>
          </div>
          <div>
            点击查看 <el-link style="font-weight:800" type="danger" @click.native="openNoteFile()">关于2021年度管理机构和教辅机构考核工作的报告</el-link>
          </div>
        </div>
        <el-card shadow="never">
          <el-row>
            <el-col :span="1" class="tableHead">序号</el-col>
            <el-col :span="6" class="tableHead">考核对象</el-col>
            <el-col :span="3" class="tableHead">状态</el-col>
            <el-col :span="7" class="tableHead">打分</el-col>
            <el-col :span="6">
              <el-tooltip placement="top" effect="light">
                <template #content> 保存并不会参与最后的计算<br />请确认后点击提交！</template>
                <el-button size="small" type="success" :disabled="allSubmitList[index]" @click="saveAll(index)" >一键保存</el-button>
              </el-tooltip>
              <el-button size="small" type="primary" :disabled="allSubmitList[index]" @click="submitAll(index)" >一键提交</el-button>
            </el-col>
          </el-row>
        </el-card>
        <el-card shadow="never" v-for="(score,index) in scoreList[index]" :key="score.id">
          <el-row>
            <el-col :span="1">{{index + 1}}</el-col>
            <el-col :span="6"><el-link type="primary" @click.native="openFile(score.furl)">{{score.bpname}}</el-link></el-col>
            <el-col :span="3">
              <el-tag v-if="score.status=='保存'" type="success">{{score.status}}</el-tag>
              <el-tag v-else-if="score.status=='提交'" >{{score.status}}</el-tag>
              <el-tag v-else type="warning">{{score.status}}</el-tag>
            </el-col>
            <el-col :span="7">
              <el-radio-group v-model="score.score">
                <el-radio :disabled="score.status == '提交'" v-for="(ts,tsindex) in score.tscore.split(',')" :key="ts" :label="ts">{{ score.tscorename.split(',')[tsindex] }}</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="6">
               <el-tooltip placement="top" effect="light">
                <template #content> 保存并不会参与最后的计算<br />请确认后点击提交！</template>
                <el-button :disabled="score.status == '提交'"  size="small" type="success" @click="roleSave(score)">保存</el-button>
              </el-tooltip>
              <el-button :disabled="score.status == '提交'"  size="small" type="primary" @click="roleSubmit(score)">提交</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="dialogFormVisible" title="修改密码">
      <el-form :ref="changePwdRef" :model="form">
        <el-form-item label="旧密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="form.pwd" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="form.newPwd" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="form.confirmPwd" show-password autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPwd">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, toRefs, ref } from 'vue';
import service from '/@/utils/request';
import axios from 'axios';
import { ElMessage,ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
import { resetRoute } from '/@/router/index';
import { useRouter } from 'vue-router';
export default {
  setup(){
    const changePwdRef = ref()
    const state = reactive({
      formLabelWidth:'120px',
      activeName: '',
      userName:'',
      userDid:'',
      assName:'',
      startTime:'',
      endTime:'',
      itemList:[],
      dialogFormVisible:false,
      form:{
        account:'',
        pwd:'',
        newPwd:'',
        confirmPwd:''
      },
      // allSubmit:false,
      allSubmitList:[],
      allScoreList:[],
      scoreList:[],
      scoreTypeId:[],
      scoreTypeName:[],
      scoreTypeBRoleId:[],
      scoreScores:[],
      scoreName:[],
      scoreMaxNum:[],
      scoreNum:[],
      baseUrl: import.meta.env.VITE_API_URL

    })
    const userInfo = Session.get('userInfo')
    state.userName = userInfo.userName
    state.userDid = userInfo.userDid
    state.form.account = userInfo.userId

    const getData = async (newPage) => {
      let dataMap = await service.get("/api/ascore/getList",{params: {searchInfo:{apid:userInfo.userId}}})
      state.itemList.splice(0,state.itemList.length)
      state.allScoreList.splice(0,state.allScoreList.length)
      state.scoreList.splice(0,state.scoreList.length)
      state.scoreNum.splice(0,state.scoreNum.length)
      state.allSubmitList.splice(0,state.allSubmitList.length)

      state.itemList = dataMap.data.itemList
      if(newPage){ state.activeName = state.itemList[0] }
      state.allScoreList = dataMap.data.scoreList
      // scoreList 每一项的分数
      state.itemList.forEach(item =>{
        let itemOneList = []
        
        for (let index = 0; index < dataMap.data.scoreList.length; index++) {
          if (item == dataMap.data.scoreList[index].itname) {
            itemOneList.push(dataMap.data.scoreList[index])
          }
          if (!state.scoreTypeId.includes(dataMap.data.scoreList[index].tid) ) {
            state.scoreTypeId.push(dataMap.data.scoreList[index].tid)
            state.scoreTypeName.push(dataMap.data.scoreList[index].tname)
            state.scoreTypeBRoleId.push(dataMap.data.scoreList[index].brid)
            state.scoreMaxNum.push(dataMap.data.scoreList[index].tmaxnum.split(','))
            state.scoreName.push(dataMap.data.scoreList[index].tscorename.split(','))
            state.scoreScores.push(dataMap.data.scoreList[index].tscore.split(','))
          }
        }
        state.scoreList.push(itemOneList)
      })
      // let submitSum = 0;
      
      for (let a = 0; a < state.scoreScores.length; a++) {
        state.scoreNum.push(new Array(state.scoreScores[a].length).fill(0))
      }

      for (let index = 0; index < dataMap.data.scoreList.length; index++) {
        let item = dataMap.data.scoreList[index] // 一项
        // if (item.status == '提交') {
        //   submitSum = submitSum + 1
        // }
        let plac = state.scoreTypeId.indexOf(item.tid) // 评分项位置

        let tscore = item.tscore.split(',') // 每一项分数
        
        for (let i = 0; i < tscore.length; i++) {
          if (item.score == tscore[i] && item.bpid != state.userDid) {
            state.scoreNum[plac][i] = state.scoreNum[plac][i] + 1
          }
        }
      }

      for (let a = 0; a < state.scoreList.length; a++) {
        let sum = 0;
        for (let b = 0; b < state.scoreList[a].length; b++) {
          if (state.scoreList[a][b].status=='提交'){
            sum =  sum + 1
          }
        }
        if(sum == state.scoreList[a].length){
          state.allSubmitList.push(true)
        }else{
          state.allSubmitList.push(false)
        }
      }
      let tempItemList = []
      let tempScoreList = []
      let tempAllSubmitList = []
      for (let c = 0; c < state.allSubmitList.length; c++) {
        if ( !state.allSubmitList[c] ) {
          tempItemList.push( state.itemList[c] )
          tempScoreList.push( state.scoreList[c] )
          tempAllSubmitList.push( state.allSubmitList[c] )
        }
      }
      state.itemList = tempItemList
      state.scoreList = tempScoreList
      state.allSubmitList = tempAllSubmitList
      if(newPage){ state.activeName = state.itemList.length > 0 ? state.itemList[0] : '' }
    }

    const getScoreNum = () =>{
      let arr = []
      for (let a = 0; a < state.scoreScores.length; a++) {
       arr.push(new Array(state.scoreScores[a].length).fill(0))
      }

      for (let index = 0; index < state.allScoreList.length; index++) {
        let item = state.allScoreList[index] // 一项
        let plac = state.scoreTypeId.indexOf(item.tid) // 评分项位置

        let tscore = item.tscore.split(',') // 每一项分数
        
        for (let i = 0; i < tscore.length; i++) {
          if (item.score == tscore[i]  && item.bpid != state.userDid) {
            arr[plac][i] = arr[plac][i] + 1
            break;
          }
        }
      }
      state.scoreNum = arr
    }
    
    const getAssData = async () => {
      let dataMap = await service.get("/admin/asetting/getList")
      state.assName = dataMap.data.data[0].name
      state.startTime = dataMap.data.data[0].stime
      state.endTime = dataMap.data.data[0].etime
    }
    getData(true)
    getAssData()

    const roleFunc = async (score,type) => {
      let plac = state.scoreTypeId.indexOf(score.tid) // 评分项位置
      
      let scoreNum = state.scoreNum[plac]

      for (let index = 0; index < state.scoreScores[plac].length; index++) {
        if (score.score == state.scoreScores[plac][index]&& score.bpid != state.userDid && score.status!='提交') {
          scoreNum[index] = scoreNum[index] + 1
        }
      }

      for (let index = 0; index < state.scoreMaxNum[plac].length; index++) {
        let scoreMaxNum = state.scoreMaxNum[plac]
        let scoreName = state.scoreName[plac]
        let scoreNum = state.scoreNum[plac]
        if ( parseInt( scoreMaxNum[index] ) < scoreNum[index] ) {
          ElMessage.warning('选择的‘'+scoreName[index]+'’数量超过最大' + scoreMaxNum[index] + '的限制')
          getData(false)
          return
        }
      }

      score.status= type
      let dataInfo = await service.post('/api/ascore/update',score)
      if (dataInfo.code === 200) { 
        ElMessage.success(type + '成功！')
        getData(false)
      } else {
        ElMessage.error(type + '失败！')
        getData(false)
      }
    }

    const roleSave = (score) => {
      roleFunc(score,"保存")
    } 

    const roleSubmit = (score) => {
      ElMessageBox.confirm(
        '确认提交信息？提交后不可修改！',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          roleFunc(score,"提交")
          // getData(false)
        })
        .catch(() => {
        })

    }
    const submitPwd = async() => {
      let dataInfo = await service.post('/api/changePwd',JSON.stringify(state.form))
      if (dataInfo.code === 200) { 
        ElMessage.success(dataInfo.msg)
        Session.clear(); // 清除缓存/token等
        resetRoute(); // 删除/重置路由
        router.push('/login');
      }

    } 

    // const roleAllFunc = async (type) => {
    //   var canSave = true
    //   getScoreNum()
    //   for (let b = 0; b < state.allScoreList.length; b++) {
    //     let score = state.allScoreList[b]
    //     let plac = state.scoreTypeId.indexOf(score.tid) // 评分项位置
    //     for (let index = 0; index < state.scoreMaxNum[plac].length; index++) {
    //       let scoreMaxNum = state.scoreMaxNum[plac]
    //       let scoreName = state.scoreName[plac]
    //       let scoreNum = state.scoreNum[plac]
    //       if ( parseInt( scoreMaxNum[index] ) < scoreNum[index]) {
    //         ElMessage.warning('选择的‘'+scoreName[index]+'’数量超过最大' + scoreMaxNum[index] + '的限制')
    //         canSave = false
    //         getData(false)
    //         return
    //       }
    //     }
    //   }

    //   if (canSave) {
    //     state.allScoreList.forEach(score=>{
    //       if(score.status != '提交'){
    //         score.status= type
    //       }
    //     })
    //     let dataInfo = await service.post('/api/ascore/updateBatch',state.allScoreList)
    //     if (dataInfo.code === 200) { 
    //       ElMessage.success(type+'成功！')
    //       getData()
    //     } else {
    //       ElMessage.error(type+'失败！')
    //       getData()
    //     }
    //   }
    // }
    
    
    const roleAllPageFunc = async (type,index) => {
      var canSave = true
      getScoreNum()
      for (let b = 0; b < state.scoreList[index].length; b++) {
        let score = state.scoreList[index][b]
        let plac = state.scoreTypeId.indexOf(score.tid) // 评分项位置
        for (let index = 0; index < state.scoreMaxNum[plac].length; index++) {
          let scoreMaxNum = state.scoreMaxNum[plac]
          let scoreName = state.scoreName[plac]
          let scoreNum = state.scoreNum[plac]
          if ( parseInt( scoreMaxNum[index] ) < scoreNum[index]) {
            ElMessage.warning('选择的‘'+scoreName[index]+'’数量超过最大' + scoreMaxNum[index] + '的限制')
            canSave = false
            getData(false)
            return
          }
        }
      }

      if (canSave) {
        state.scoreList[index].forEach(score=>{
          if(score.status != '提交'){
            score.status= type
          }
        })
        let dataInfo = await service.post('/api/ascore/updateBatch',state.scoreList[index])
        if (dataInfo.code === 200) { 
          ElMessage.success(type+'成功！')
          getData()
        } else {
          ElMessage.error(type+'失败！')
          getData()
        }
      }
    }
    const submitAll = (index) => {
      ElMessageBox.confirm(
        '确认提交全部信息？提交后不可修改！',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          roleAllPageFunc('提交', index)
        })
        .catch(() => {
        })
    }
    
    const saveAll = (index) => {
      roleAllPageFunc('保存', index)
    }

    const router = useRouter();
    const onHandleCommandClick = () => {
				ElMessageBox({
					closeOnClickModal: false,
					closeOnPressEscape: false,
					title: "提示",
					message: "确认退出登录",
					showCancelButton: true,
					confirmButtonText: "确认",
					cancelButtonText: "取消",
					beforeClose: (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = "退出";
							setTimeout(() => {
								done();
								setTimeout(() => {
									instance.confirmButtonLoading = false;
								}, 300);
							}, 700);
						} else {
							done();
						}
					},
				})
					.then(() => {
						Session.clear(); // 清除缓存/token等
						resetRoute(); // 删除/重置路由
						router.push('/login');
					})
					.catch(() => {});
		}
    const openFile = (furl)=>{
      axios({
        method: 'get',
        url: state.baseUrl + furl,
        responseType:'arraybuffer'
      }) 
      .then((response)=> {
        let blob = new Blob([response.data], { type: 'application/pdf;chartset=UTF-8' })
        let url = URL.createObjectURL(blob)
        window.open(url)
      });
		}
    const openNoteFile = ()=>{
      window.open('../../../note.pdf')
      // axios({
      //   method: 'get',
      //   url: state.baseUrl + furl,
      //   responseType:'arraybuffer'
      // }) 
      // .then((response)=> {
      //   let blob = new Blob([response.data], { type: 'application/pdf;chartset=UTF-8' })
      //   let url = URL.createObjectURL(blob)
      //   window.open(url)
      // });
		}
    return {
      ...toRefs(state),
      changePwdRef,
      roleSave,
      openFile,
      openNoteFile,
      roleSubmit,
      submitAll,
      saveAll,
      submitPwd,
      onHandleCommandClick
    }
  }

}
</script>

<style lang="scss" >
.title{
  // text-align: left;
}
.logoLine{
  padding-top: 20px;
  display: inline-block;
  line-height: 50px;
  font-size: xx-large;
  text-align: center;
  vertical-align: middle;
  font-weight: 800;
  margin-left: -50px;
  letter-spacing: 0.2em;
}
.icon{
  width: 15px;
  height: 15px;
  margin-right: 3px;
  display: inline-block;
  vertical-align: middle;
}
.search{
  display: inline-block;
  vertical-align: middle;
}
.mainPain{
  width: 90%;
  margin: 0 auto;
}
.tab-pane{
  height:75vh;
  overflow-y:auto;
  overflow-x:hidden;
}
.el-card{
  // width: 80%;
  margin: 0 auto;
}

.el-col{
  text-align: center;
}
.headBar{
  width: 90%;
  height: 108px;
  margin: 0 auto;
  padding: 3px;
  
  background: url('../../../public/bimg.jpg') no-repeat;

}
.infoRow{
  padding: 3px;
}
.fontColor{
  padding-top: 50px;
  color: #333;
  font-size: large;
  font-weight: 500;
}
.el-dropdown{
  vertical-align: middle;
}
.textPlac{
  padding-top: 30px;
}
.tableHead{
  font-weight: 800;
  font-size: large;
}
.assInfo{
  width:100%;

}
.assInfoBox{
  width:100%;
  margin: 0px auto 8px;
  background-color: rgb(250, 236, 216);
  border-radius: 8px;
  color: #E6A23C;
  padding: 8px;
  padding-left: 30px;
}
.fontNum{
  color: #F56C6C;
}
.fontName{
  // color: #67C23A;
}
.homeMain .el-tabs__item {
    font-size: 20px;
}

</style>
